package com.ytf.file.local;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @className FileController
 * @author YTF
 * @date 2025/5/31 17:04
 * @description
 */
@Controller
@RequiredArgsConstructor
public class FileController {

    private final FileStorageConfig fileStorageConfig;

    @GetMapping("/files")
    public String homePage(Model model) {
        List<File> files = listFiles();
        List<Map<String, String>> fileInfoList = new ArrayList<>();
        for (File file : files) {
            Map<String, String> fileInfo = new HashMap<>();
            fileInfo.put("name", file.getName());
            fileInfo.put("size", FileUtil.readableFileSize(file.length()));
            fileInfoList.add(fileInfo);
        }
        model.addAttribute("fileList", fileInfoList);
        return "uploadForm";
    }

    @PostMapping("/upload")
    public String handleFileUpload(@RequestParam("file") MultipartFile file,
                                   Model model) {
        try {
            // 获取原始文件名和扩展名
            String originalFilename = file.getOriginalFilename();
            if (StrUtil.isBlank(originalFilename)) {
                model.addAttribute("error", "文件名不能为空");
                return homePage(model);
            }

            String fileExt = FileUtil.extName(originalFilename);
            String newFileName = IdUtil.fastSimpleUUID() + "." + fileExt;

            // 创建目标文件路径
            Path uploadPath = fileStorageConfig.getUploadPath();
            Path filePath = uploadPath.resolve(newFileName);

            // 确保目录存在
            FileUtil.mkdir(uploadPath.toString());

            // 保存文件
            file.transferTo(filePath);

            model.addAttribute("message", "文件上传成功: " + newFileName);
        } catch (Exception e) {
            model.addAttribute("error", "文件上传失败: " + e.getMessage());
        }

        return homePage(model);
    }

    @GetMapping("/download/{fileName}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) {
        Path uploadPath = fileStorageConfig.getUploadPath();
        Path filePath = uploadPath.resolve(fileName).normalize();
        File file = filePath.toFile();

        if (!file.exists() || file.isDirectory()) {
            return ResponseEntity.notFound().build();
        }

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"");
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");

        // 创建资源对象
        Resource resource = new InputStreamResource(FileUtil.getInputStream(file));

        return ResponseEntity.ok()
                .headers(headers)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .contentLength(file.length())
                .body(resource);
    }

    @GetMapping("/view/{fileName}")
    public String viewFile(@PathVariable String fileName, Model model) {
        Path uploadPath = fileStorageConfig.getUploadPath();
        Path filePath = uploadPath.resolve(fileName).normalize();
        File file = filePath.toFile();

        if (!file.exists() || file.isDirectory()) {
            model.addAttribute("error", "文件不存在");
            return homePage(model);
        }

        model.addAttribute("file", file.getName());
        model.addAttribute("size", FileUtil.readableFileSize(file.length()));
        model.addAttribute("type", FileUtil.getMimeType(file.getPath()));

        return "download";
    }

    private List<File> listFiles() {
        try {
            Path uploadPath = fileStorageConfig.getUploadPath();
            File uploadDir = uploadPath.toFile();

            if (uploadDir.exists() && uploadDir.isDirectory()) {
                return FileUtil.loopFiles(uploadDir);
            }
        } catch (Exception e) {
            // 忽略错误
        }
        return new ArrayList<>();
    }
}